<?php

/**
 * Common utilities
 * @author ntourne
 * @date 24/05/2011
 */

class Utilities {
	

	/**
	 * Return only the GET params (like action=createperson&firstname=&lastname=...)
	 * @return current URL 
	 */
	public static function getCurrentURL() {
		//$url = ltrim($_SERVER["REQUEST_URI"], "/");
		$url = $_SERVER["REQUEST_URI"];
		return $url;
	}


	/**
	 * Encode an URL to send as GET param
	 * @return encoded URL
	 */
	public static function encodeURL($url) {
		$url = str_replace("/","_", $url);
		$url = str_replace("&",":", $url);
		$url = urlencode($url);
		return $url;
	}
	

	/**
	 * De-encode an URL get as GET param
	 * @return de-encode URL
	 */
	public static function deEncodeURL($url) {
		$url = urldecode($url);
		$url = str_replace(":", "&", $url);
		$url = str_replace("_", "/", $url);
		return urldecode($url); 
	}
	
	
	/**
	 * Return true if the captcha is valid (using REcaptcha web service)
	 * @return boolean
	 */
	public static function isValidRecaptcha($recaptcha_challenge_field, $recaptcha_response_field, $recaptcha_privatekey) {
		require_once('libs/recaptcha-php-1.11/recaptchalib.php');
		$resp = recaptcha_check_answer ($recaptcha_privatekey,
	    							$_SERVER["REMOTE_ADDR"],
									$recaptcha_challenge_field,
									$recaptcha_response_field);
		return ($resp->is_valid);
	}

	
	/**
	 * Receive points as -2, -1, 0, 1, 2; and return a number between 0 and 100
	 * @param int $points
	 * @return double $normalizePoints
	 */
	public static function normalizePoints($points) {
		
	
		// re-fix out of range cases - TODO that's necessary?
		if ($points < 0)
			$points = 0;
		if ($points > 100)
			$points = 100;
		
		// rounds (removes number of digits after the decimal points)
		$points = round($points, 0);
			
		return $points;
	}
	

	/**
	 * Calculate time ago
	 * @param datetime $date (mysql format)
	 * @param int $granularity
	 */
	public static function getTimeAgo($date,$granularity=1) {
	    $date = strtotime($date);
	    $difference = time() - $date;
	    $periods = array('decade' => 315360000,
	        'year' => 31536000,
	        'month' => 2628000,
	        'week' => 604800, 
	        'day' => 86400,
	        'hour' => 3600,
	        'minute' => 60,
	        'second' => 1);
	                                 
	    foreach ($periods as $key => $value) {
	        if ($difference >= $value) {
	            $time = floor($difference/$value);
	            $difference %= $value;
	            $retval .= ($retval ? ' ' : '').$time.' ';
	            $retval .= (($time > 1) ? $key.'s' : $key);
	            $granularity--;
	        }
	        if ($granularity == '0') { break; }
	    }
	    return $retval;      
	}

	
	/**
	 * Remove all special chars
	 * @param string $text
	 * @return $clean
	 */
	public static function removeSpecialChars($text) {
		$clean = preg_replace("/^[^a-z0-9]?(.*?)[^a-z0-9]?$/i", "$1", $text);
		$clean = ucfirst($clean); 
		$clean = ucfirst(strtolower($clean));
		return $clean;
	}
	
	
	/**
	 * i18n all messages array in a new message array
	 * @param array<Message> $messages
	 * 
	 */
	public static function i18nMessages($messages, $smarty) {
		$newMessages = array();
		foreach($messages as $message) {
			if (Validation::isEmptyString($message['text']))
				$message['text'] = $smarty->get_config_vars($message['code']);
			$newMessages[] = $message;
		}
		return $newMessages;
	} 

	
	function array2json($arr) {
	    if(function_exists('json_encode')) return json_encode($arr); //Lastest versions of PHP already has this functionality.
	    $parts = array();
	    $is_list = false;
	
	    //Find out if the given array is a numerical array
	    $keys = array_keys($arr);
	    $max_length = count($arr)-1;
	    if(($keys[0] == 0) and ($keys[$max_length] == $max_length)) {//See if the first key is 0 and last key is length - 1
	        $is_list = true;
	        for($i=0; $i<count($keys); $i++) { //See if each key correspondes to its position
	            if($i != $keys[$i]) { //A key fails at position check.
	                $is_list = false; //It is an associative array.
	                break;
	            }
	        }
	    }
	
	    foreach($arr as $key=>$value) {
	        if(is_array($value)) { //Custom handling for arrays
	            if($is_list) $parts[] = array2json($value); /* :RECURSION: */
	            else $parts[] = '"' . $key . '":' . array2json($value); /* :RECURSION: */
	        } else {
	            $str = '';
	            if(!$is_list) $str = '"' . $key . '":';
	
	            //Custom handling for multiple data types
	            if(is_numeric($value)) $str .= $value; //Numbers
	            elseif($value === false) $str .= 'false'; //The booleans
	            elseif($value === true) $str .= 'true';
	            else $str .= '"' . addslashes($value) . '"'; //All other things
	            // :TODO: Is there any more datatype we should be in the lookout for? (Object?)
	
	            $parts[] = $str;
	        }
	    }
	    $json = implode(',',$parts);
	    
	    if($is_list) return '[' . $json . ']';//Return numerical JSON
	    return '{' . $json . '}';//Return associative JSON
	} 

	
	
	/**
	 * Add link to @username data
	 * @param String $text
	 */
	function linkify($text) {
	    $text = preg_replace('/(^|\s)@(\w+)/', '\1<a class="normal" href="user.php?u=\2"><span class="no-underline">@</span>\2</a>', $text);
	    return preg_replace('/(^|\s)#(\w+)/', '\1<a class="normal" href="topic.php?id=\2"><span class="no-underline">#</span>\2</a>', $text);
	}
	
}